<template>
	<view class="container">
		<!-- 地图区域 -->
		<map id="deliveryMap" :longitude="center.lng" :latitude="center.lat" :markers="markers"
			style="width: 100%; height: 73vh;" @markertap="handleMarkerTap" show-location></map>
		<view class="cu-bar bg-white search fixed" :style="[{top:CustomBar + 'px'}]">
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input type="text" placeholder="输入搜索的关键词" confirm-type="search"></input>
			</view>
			<view class="action">
				<button class="cu-btn bg-gradual-green shadow-blur round">搜索</button>
			</view>
		</view>
		<view class="expandable-box" v-if="boxTrue" @touchstart="onTouchStart" @touchmove="onTouchMove"
			@touchend="onTouchEnd" :style="{
			    'transform': `translate(0, ${offsetY}px)`,
			    // 'overflow-y': isOverflow ? 'auto' : 'hidden',
				 'transition': isTransition? '.5s': 'none',// 动态控制滚动
			  }">
			<view v-for="(item, index) in deliveryPoints" @click="selectItem(item)" :key="item.id" class="list-item">
				<view class="item-header">
					<text class="name">{{ item.name }}</text>
					<text class="distance">{{ item.distance }}米</text>
				</view>
				<view class="item-address">{{ item.area }}</view>
			</view>
		</view>


		<view class="expandable-boxs" v-else style="">
			{{form.name}}
			<button @click="selectPoint">选择</button>
		</view>




	</view>
</template>

<script>
	import {
		generateSignatureGet
	} from '@/utils/signature.js';
	import configData from '@/common/config.js'
	import {
		format
	} from 'crypto-js';
	import {
		calculateDistance
	} from '@/utils/ruoyi.js'
	export default {
		data() {
			return {
				mapKey: configData.MapKey,
				CustomBar: this.CustomBar,
				startY: 0,
				offsetY: 50,
				recordOffsetY: 0,
				center: {
					lng: 112.43705651,
					lat: 34.67254951
				}, //快递发货点位置
				markers: [],
				polyline: [],
				deliveryPoints: [],
				activeId: null,
				isOverflow: false, // 新增状态
				isTransition: false, // 新增状态
				screenWidth: 0, // 屏幕物理宽度（单位：px）
				screenHeight: 0, // 屏幕物理高度（单位：px）
				windowHeight: 0, // 可用窗口高度（含状态栏）
				num: 1,
				childTop: 0,
				childTops: 0,

				queryForm: {
					lng: '',
					lat: '',
					areaCode: '',
				},
				boxTrue: true,
				form: {},
				orderList: {
					lat: "",
					lng: "",
					orderId: "",
					type: "",
				},
				distanceLimit: '',
				minDistance: '',
			};
		},

		watch: {
			offsetY(newVal, oldVal) {
				const H80 = this.screenHeight * 0.55
				const H30 = 50

				if (newVal < H30) {
					this.offsetY = H30
				} else if (newVal > H80) {
					this.offsetY = H80
				}
				// if (newVal > H80) {
				// 	this.offsetY = H80
				// }
			},

			screenHeight(newVal, oldVal) {
				// this.offsetY = newVal
			},
		},
		onLoad(option) {
			this.orderList = option


			// 是否限制到快递柜距离(1限制 2不限制)
			this.$Request.getT('/app/common/type/235').then(res => {
				if (res.code == 0) {
					if (res.data && res.data.value) {
						this.distanceLimit = res.data.value
						if (this.distanceLimit == 1) {
							// 开快递柜限制距离（米）
							this.$Request.getT('/app/common/type/232').then(request => {
								if (request.code == 0) {
									if (request.data && request.data.value) {
										this.minDistance = request.data.value
									}
								}
							});
						}
					}
				}
			});
		},

		mounted() {
			this.getUserLocation();
		},
		onReady() {
			uni.getSystemInfo({
				success: (res) => {
					this.screenWidth = res.screenWidth;
					this.screenHeight = res.screenHeight;
					this.windowHeight = res.windowHeight; // 可用窗口高度（含状态栏）
					this.offsetY = this.screenHeight * 0.55
				}
			});
		},

		methods: {


			getList() {

				this.$Request.postT('/app/point/queryNearbyCabinet', this.queryForm).then(res => {
					if (res.code == 0) {
						this.deliveryPoints = res.data
						this.generateMarkers()
					}

				});
			},

			selectPoint() {

				uni.showLoading({
					title: '加载中...',
					mask: false
				});
				if (this.distanceLimit == 1) {
					uni.getLocation({
						type: 'gcj02',
						success: (res) => {

							let distance = calculateDistance(res.latitude, res.longitude, this
								.form.lat, this.form.lng)
							if (this.minDistance && distance < this.minDistance) {
								this.openTheDoors()

							} else {
								uni.showToast({
									title: '距离过远，请前往快递柜附近',
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							console.error('获取位置失败:', err);
							uni.showToast({
								title: '获取位置失败',
								icon: 'none'
							});
						}
					});
				} else {
					this.openTheDoors()
				}

			},


			openTheDoors() {

				let data = {
					orderId: this.orderList.orderId,
					shipperCabinetPointId: this.form.id,
				}
				let datas = {
					indentId: this.orderList.orderId,
					shipperCabinetPointId: this.form.id,
				}
				this.$Request.shoppGetT('/api/huerai_kuaidigui/express_cabinet_info?cabinet_id=1').then(res => {
					if (res.data.length > 0) {
						if(this.orderList.type == 1){
							this.$Request.postT('/app/indent/addInventory', datas).then(res => {
								if (res.code == 0) {
									uni.showToast({
										title: '柜门已打开',
										icon: 'success'
									});
									setTimeout(() => {
										this.backAndRefresh()
									}, 1000)
								}
							});
						}else if(this.orderList.type == 2){
							this.$Request.postT('/app/logisticsOrder/addInventory', data).then(res => {
								if (res.code == 0) {
									uni.showToast({
										title: '柜门已打开',
										icon: 'success'
									});
									setTimeout(() => {
										this.backAndRefresh()
									}, 1000)
								}
							});
						}
						
					} else {
						uni.showToast({
							title: '快递柜已满',
							icon: 'none'
						});
					}
					uni.hideLoading();
				}).catch(error => {
					console.log(error);
					uni.hideLoading();
				})
			},


			backAndRefresh() {
				const pages = getCurrentPages();
				const prevPage = pages[pages.length - 2]; // 获取上级页面实例
				uni.navigateBack({
					delta: 1,
					success: () => {
						prevPage.$vm.userList(); // 调用上级页面的刷新方法
					}
				});
			},



			// 根据订单发货点经纬度获取周围快递柜点位
			async getUserLocation() {

				this.center.lng = this.orderList.lng;
				this.center.lat = this.orderList.lat;
				const areaList = await this.latLngQueryAddress(this.orderList.lat, this.orderList.lng)
				this.queryForm = {
					lng: this.orderList.lng,
					lat: this.orderList.lat,
					areaCode: areaList.ad_info.adcode,
				}
				this.addCurrentLocationMarker();
				this.getList()
			},

			//根据经纬度获取地址
			latLngQueryAddress(lat, lng) {
				return new Promise((resolve, reject) => {
					const path = '/ws/geocoder/v1';
					const params = {
						key: this.mapKey,
						location: `${lat},${lng}`
					};
					const sk = configData.SecretKey;
					const sig = generateSignatureGet(path, params, sk);
					params.sig = sig;
					const url = `https://apis.map.qq.com${path}?${this.encodeParams(params)}`;

					uni.request({
						url: url,
						success: (res) => {
							if (res.statusCode === 200) {
								// 修正数据路径（根据实际返回结构调整）
								// const address = res.data.result?.formatted_addresses?.recommend;
								resolve(res.data.result); // 成功时返回地址
							} else {
								reject(new Error('请求失败')); // 处理 HTTP 错误状态
							}
						},
						fail: (err) => {
							reject(err); // 处理网络错误
						}
					});
				});
			},


			encodeParams(params) {
				return Object.entries(params)
					.map(([key, value]) => {
						return `${key}=${encodeURIComponent(value)}`
					})
					.join('&')
			},



			// 添加发货地点标记
			addCurrentLocationMarker() {
				this.markers.push({
					id: 0,
					longitude: this.center.lng,
					latitude: this.center.lat,
					iconPath: '../../static/image/location.png',
					width: 30,
					height: 30,
					callout: {
						content: '发货地点',
						color: '#000',
						fontSize: 14,
						borderRadius: 4,
						bgColor: '#fff',
						padding: 4,
						display: 'ALWAYS'
					}
				});
			},
			// 生成快递柜标记点
			generateMarkers() {
				this.deliveryPoints.forEach(point => {
					this.markers.push({
						id: point.id,
						longitude: point.lng,
						latitude: point.lat,
						iconPath: '../../static/image/guizi.png',
						width: 30,
						height: 30,
						callout: {
							content: `${point.name}\n${point.distance}米`,
							color: '#fff',
							fontSize: 14,
							borderRadius: 4,
							bgColor: '#007AFF',
							padding: 4,
							display: 'BYCLICK'
						}
					});
				});
			},
			handleMarkerTap(e) {
				console.log(e);
			},

			// 选择快递柜点位
			selectItem(item) {
				this.activeId = item.id;
				this.center = {
					lng: item.lng,
					lat: item.lat
				};
				this.form = this.deliveryPoints.find(res => res.id == this.activeId)
				this.zoomToLocation(item);
				this.boxTrue = false
			},
			// 缩放至指定位置
			zoomToLocation(point) {
				uni.createMapContext('deliveryMap').moveToLocation({
					latitude: point.lat,
					longitude: point.lng,
					duration: 500
				});
			},

			onTouchStart(e) {

				this.startY = e.touches[0].clientY - this.offsetY;
			},

			onTouchMove(e) {
				this.offsetY = e.touches[0].clientY - this.startY;
			},

			onTouchEnd() {
				const H55 = this.screenHeight * 0.55
				const H25 = this.screenHeight * 0.25
				if (this.num == 1) {
					if (this.offsetY < H25) {
						this.offsetY = 50
						this.num = 2
					}
					if (this.offsetY > H25) {
						this.offsetY = H55
					}

				} else if (this.num == 2) {
					console.log(this.offsetY);
					// if (this.offsetY > 50) {
					// 	this.offsetY = 50
					// 	// this.num = 1
					// }
				}

				this.isTransition = true
				setTimeout(() => {
					this.isTransition = false
				}, 500)
			},



		}
	};
</script>

<style scoped lang="scss">
	.container {
		height: 100vh;
		position: relative;
		overflow: hidden;
	}

	.map-container {
		overflow: hidden;
	}

	.list-container {
		overflow: hidden;
		background: #fff;
		transition: height 0.3s ease;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
	}

	.toggle-btn {
		padding: 15px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #f5f5f5;
	}

	.toggle-btn image {
		width: 24px;
		height: 24px;
	}

	.list-content {
		padding: 15px;
	}

	.list-item {
		padding: 15px;
		margin-bottom: 10px;
		background: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.list-item.active {
		background: #e3f2fd;
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 5px;
	}

	.name {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.distance {
		color: #888;
		font-size: 14px;
	}

	.item-address {
		font-size: 14px;
		color: #666;
	}


	.expandable-box {
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		min-height: calc(100vh - 50px);
		// height: 40vh;
		z-index: 999;

		background: linear-gradient(to bottom, rgba(245, 245, 245, 0) 0%, rgba(245, 245, 245, 1) 50rpx, rgba(245, 245, 245, 1) 100%);
		padding: 30rpx 30rpx;

	}

	.expandable-boxs {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100vw;
		height: 40vh;
		z-index: 999;

		background: linear-gradient(to bottom, rgba(245, 245, 245, 1) 0%, rgba(245, 245, 245, 1) 100%);
		padding: 30rpx 30rpx;

	}
</style>